package com.tanchengjin.admin.aop.needRole;

import com.tanchengjin.admin.exception.ApplicationException;
import com.tanchengjin.admin.exception.NeedPermissionException;
import com.tanchengjin.admin.model.pojo.AdminRole;
import com.tanchengjin.admin.service.AdministratorService;
import com.tanchengjin.admin.utils.ServerResponse;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;

/**
 * 角色权限切面
 *
 * @author TanChengjin
 * @version v1.0.0
 * @email 18865477815@163.com
 */
@Aspect
@Component
public class NeedRoleAspect {
    private final static Logger logger = LoggerFactory.getLogger(NeedRoleAspect.class);
    @Autowired
    private AdministratorService administratorService;

    @Pointcut(value = "@annotation(com.tanchengjin.admin.aop.needRole.NeedRole)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        logger.info("around");
        //通过反射拿到注解
        Method m = ((MethodSignature) (point.getSignature())).getMethod();
        NeedRole annotation = m.getAnnotation(NeedRole.class);

        String[] roles = annotation.value();
        if (roles.length != 0) {
            logger.info("角色权限拦截开启");
            String role = roles[0];
            List<AdminRole> roleList = administratorService.getRoles();
            for (AdminRole adminRole : roleList) {
                if (adminRole.getRole().equals(role)) {
                    return point.proceed();
                }
            }

            NeedRole.ResponseType responseType = annotation.responseType();
            if (responseType == NeedRole.ResponseType.REST) {
                throw new NeedPermissionException("权限不足");
            } else if (responseType == NeedRole.ResponseType.HTML) {
                ServletRequestAttributes requestAttributes = (ServletRequestAttributes) (RequestContextHolder.getRequestAttributes());
                HttpServletRequest request = requestAttributes.getRequest();
                HttpServletResponse response = requestAttributes.getResponse();
                response.sendRedirect(request.getContextPath() + "/auth/login");
            }
        }
        return null;
    }
}
